#!/bin/bash

#code repo
#If not given in env, using default 
#If default not exit, clone from url($3)
DEFAULT_CODE_REPO=/root/git-repo
#output 
#If not given in env, using default
DEFAULT_OUTPUT=/root/tarball

PACKAGE=$1
CODE_REPO=${CODE_REPO:-$DEFAULT_CODE_REPO}
#docer pypiserver map local package to /opt/pypi
#we can upload tarball local
PYPI_LOCAL_PACKAGE_DIR=${PYPI:-$DEFAULT_OUTPUT}
TAG=$2

#rpm official package release number
declare -A PACKAGE_VERSION_MAPPING
PACKAGE_VERSION_MAPPING=(
[keystone]="8.0.0.1"
[python-keystoneclient]="1.7.2.1"
[nova]="12.0.0.1"
[python-novaclient]="2.30.1.1"
[neutron]="7.0.0.2"
[python-neutronclient]="3.1.0.1"
[cinder]="7.0.0.1"
[python-cinderclient]="1.4.0.1"
[glance]="11.0.0.1"
[python-glanceclient]="1.1.0.1"
[ceilometer]="5.0.0.1"
[python-ceilometerclient]="1.5.0.1"
[heat]="5.0.0.1"
[python-heatclient]="0.8.0.1"
[oslo.db]="2.6.0.1"
)

PACKAGE_BASE_VERSION=${PACKAGE_VERSION_MAPPING["${PACKAGE}"]}

BuildTarball()
{
    local tmp_dir=$(mktemp -d)
    cp ${CODE_REPO}/${PACKAGE} ${tmp_dir}/${PACKAGE} -R
    cd ${tmp_dir}/${PACKAGE}
    git checkout ${TAG}
    #echo ${tmp_dir}
    OSLO_PACKAGE_VERSION=${PACKAGE_BASE_VERSION} python setup.py sdist
    #will be changed with rsync 
    cp ./dist/${PACKAGE}-${PACKAGE_BASE_VERSION}.tar.gz ${PYPI_LOCAL_PACKAGE_DIR}/
    rm -rf ${tmp_dir}
}

main()
{
    if [ ! -d "${CODE_REPO}/${PACKAGE}" ];then
        if [ 3 -ne $# ];then
            echo "You must define CODE_REPO or pass url"
            exit 1
        fi
        package="$(echo $3 | awk '{len=split($0, ret, "/");print ret[len]}')"
        echo ${package}
        if [ "${PACKAGE}" != "${package%.*}" ]; then
            echo "Package error"
        fi
        git clone $3 ${CODE_REPO}/${PACKAGE}
    fi

    BuildTarball
}


#args
#$1: package name
#$2: your private tag
#$3: your git server url
#$1,$2 is required, $3 is option
main "$@"
